function outarray = colcode2uint32(inarray)
% colcode2uint32  - convert from colcode to uint32 array
%
% FORMAT:       outarray = colcode2uint32(inarray)
%
% Input fields:
%
%       inarray     Nx4 input array of type colcolde
%                   (n, 1) = color index or NaN
%                   (n, 2) = red component (0...255)
%                   (n, 3) = green component (0...255)
%                   (n, 4) = blue component (0...255)
%
% Output fields:
%
%       outarray    Nx1 uint32 array
%
% See also uint322colcode

% Version:  v0.7f
% Build:    8110521
% Date:     Nov-05 2008, 9:00 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin ~= 1 || ...
   ~isa(inarray, 'double') || ...
   ~isreal(inarray) || ...
    issparse(inarray) || ...
    ndims(inarray) ~= 2 || ...
    size(inarray, 2) ~= 4
    error( ...
        'BVQXtools:BadArgument', ...
        'Bad/missing input argument supplied.' ...
    );
end

% produce output array
outarray = uint32(zeros(size(inarray, 1), 1));

% leave if empty
if isempty(inarray)
    return;
end

% force RGB in RGB(:, [2, 3, 4])
for cc = 2:4
    inarray(isinf(inarray(:, cc)), cc) = 0;
    inarray(isnan(inarray(:, cc)), cc) = 0;
    inarray(inarray(:, cc) < 0   , cc) = 0;
    inarray(inarray(:, cc) > 255 , cc) = 255;
end
inarray = fix(inarray);

% rgbcolormod/min, rfactor, gfactor
rgbcolortot = 256 * 16777216;
rgbcolormin = 63 * 16777216;
rfactor = 65536;
gfactor = 256;

% get colors with indices
rgbcolor = isnan(inarray(:, 1));

% set index color
outarray(~rgbcolor) = uint32(mod(inarray(~rgbcolor, 1), rgbcolortot));

% fill those correctly
outarray(rgbcolor) = uint32(rgbcolormin + ...
    rfactor .* inarray(rgbcolor, 2) + ...
    gfactor .* inarray(rgbcolor, 3) + ...
    inarray(rgbcolor, 4));
